<template>
	<div class="echart" ref="myChartRef"></div>
</template>
  
<script setup>
import { ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { useEventListener } from '/@/jqkit/jqkComposables/useEvent'
import { debounce } from 'lodash';

const props = defineProps({
	dataSource: {
		type: Object,
		default: null,
	},
});

const title = ref('');
const subTitle = ref('');
const seriesName = ref('');
const pieData = ref([]);
const myChartRef = ref(null);
let myChart = null;
let timer = null;

const handleDataSource = (obj) => {
	if (!obj) return;
	// console.log("当前组件接收数据源为：", obj);
	
	title.value = obj.title || '';
	subTitle.value = obj.subTitle || '';
	seriesName.value = obj.seriesName || '';
	pieData.value = obj.pieData || [];

	nextTick(() => {
		initChart();
		resizeChart();
	});
};

// 监听 props.dataSource 的变化
watch(() => props.dataSource, (newVal) => {
	handleDataSource(newVal);
}, { immediate: true,  deep: true });

// 获取 series 数据
const getSeries = (pieData) => {
	return pieData.map((item) => ({
		name: seriesName.value,
		type: 'pie',
		radius: '50%',
		data: pieData || [],
		emphasis: {
			itemStyle: {
				shadowBlur: 10,
				shadowOffsetX: 0,
				shadowColor: 'rgba(0, 0, 0, 0.5)'
			}
		}
	}));
};

// 获取 echart 配置项
const getOption = () => {
	return {
		title: {
			text: title.value,
			subtext: subTitle.value || '',
			left: 'center'
		},
		tooltip: {
			trigger: 'item'
		},
		legend: {
			orient: 'vertical',
			left: 'left'
		},
		series: getSeries(pieData.value)
	};
};

// 初始化 echart 图表
const initChart = () => {
	if (!myChartRef.value) return;

	const chartDom = document.getElementById(myChartRef.value.id);
	if (!chartDom) return;

	echarts.dispose(chartDom);
	myChart = echarts.init(chartDom);
	const option = getOption();
	option && myChart.setOption(option);
};

// 重置 echart 尺寸
const resizeChart = debounce(() => {
	if (myChart) myChart.resize();
}, 200);
useEventListener(window, 'resize', resizeChart)
</script>
  
<style scoped lang="scss">
.echart {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-color: #fff;
}
</style>